/// author stevenHu
///
/// created by hujintao
/// created at 2022/3/16
import 'package:shared_preferences/shared_preferences.dart';

///缓存管理类
class HkCache {
  SharedPreferences? prefs;

  HkCache._() {
    init();
  }

  static HkCache? _instance;

  HkCache._pre(this.prefs);

  ///预初始化，防止在使用get时，prefs还未完成初始化
  static Future<HkCache> preInit() async {
    if (_instance == null) {
      var prefs = await SharedPreferences.getInstance();
      _instance = HkCache._pre(prefs);
    }
    return _instance!;
  }

  static HkCache getInstance() {
    _instance ??= HkCache._();
    return _instance!;
  }

  void init() async {
    prefs ??= await SharedPreferences.getInstance();
  }

  static setString(String key, String value) {
    HkCache.getInstance().prefs?.setString(key, value);
  }

  static setDouble(String key, double value) {
    HkCache.getInstance().prefs?.setDouble(key, value);
  }

  static setInt(String key, int value) {
    HkCache.getInstance().prefs?.setInt(key, value);
  }

  static setBool(String key, bool value) {
    HkCache.getInstance().prefs?.setBool(key, value);
  }

  static setStringList(String key, List<String> value) {
    HkCache.getInstance().prefs?.setStringList(key, value);
  }

  static Object? get<T>(String key) {
    return HkCache.getInstance().prefs?.get(key);
  }

  static String? getString<T>(String key) {
    return HkCache.getInstance().prefs?.getString(key);
  }

  static bool? getBool<T>(String key) {
    return HkCache.getInstance().prefs?.getBool(key);
  }

  static int? getInt<T>(String key) {
    return HkCache.getInstance().prefs?.getInt(key);
  }

  static List<String> getStringList(key) {
    var result = HkCache.getInstance().prefs?.getStringList(key);
    return result ?? [];
  }

  static double? getDouble<T>(String key) {
    return HkCache.getInstance().prefs?.getDouble(key);
  }

  static bool? containsKey<T>(String key) {
    return HkCache.getInstance().prefs?.containsKey(key);
  }

  // 判断key是否存在
  static bool hasKey(key) {
    return HkCache.getInstance().prefs?.containsKey(key) ?? false;
  }

  static Future<bool?> remove(String key) async {
    return await HkCache.getInstance().prefs?.remove(key);
  }

  static clearAllKeys() {
    HkCache.getInstance().prefs?.clear();
  }
}
